package com.example.cs342messenger;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import basicClasses.LoginObject;
import basicClasses.MessageObject;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class Messages extends Activity {
	
	protected MessageObject message;
	protected String sender;

	private com.example.cs342messenger.MessageListViewAdapter adapter;

	//hard coded  will need to change via db or intent 
	private String user;
	private String buddy;
	SharedPreferences mPrefs;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_messages);
		
		Intent intent = getIntent();
		buddy = intent.getStringExtra("buddy");
		//Toast.makeText(this, buddy, Toast.LENGTH_SHORT).show();
		
		
		
		
		//Jacob's test
		
		/*
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
		    sender = extras.getString("sender");
		    message = new MessageObject("jake@jake.com",sender,"this is a test message");
		    SendMessageTask sendMessage = new	SendMessageTask();
		    sendMessage.execute(message);
		}
		*/
		/*
		List<Comment> test = new ArrayList<Comment>();
  		for(int i =0; i< 32; i++){
  			Comment com = new Comment();
  			com.setComment("HEllo Worldajsfklajsf;lkajsfkl;ajsfkljaldsfjlajsf;ljas;ldfj;lasjgfasdgjadsjfajsflhadsjghjadsgkljasd;lghaldskjgklasjhasjfakldsjgjhagkljaslkghadksjgklsjghasg;ashgklasjdgklasjd;g " + i);
  			com.setNum(i);
  			test.add(com);
  		}*/

		mPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
		user = mPrefs.getString("user", "NA");
		String newUpdate = mPrefs.getString("updates", "none");
		if(!newUpdate.equals("none")){
			String delims = "[ ]+";
			String[] theUpdates = newUpdate.split(delims);
			newUpdate = "";
			for(int i = 0; i < theUpdates.length; i++){
				if(!buddy.equals(theUpdates[i])){
					newUpdate = newUpdate + " " + theUpdates[i];
				}
			}
			SharedPreferences.Editor edit = mPrefs.edit();
			edit.putString("updates", newUpdate);
			edit.commit();
		}
		new PopulateContactMain().execute();
		System.out.println("MESSAGES USER: " + user);
  		final Button send = (Button) findViewById(R.id.sendMessage);
  		final EditText message = (EditText) findViewById(R.id.message);
        send.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
               
               String str = message.getText().toString();
               Comment com= new Comment();
               MessageObject mess = new MessageObject();
               
               com.setComment(str);
               mess.setText(str);
               
               com.setReciever(buddy);
               mess.setReciever(buddy);
               com.setUser(user);
               mess.setSender(user);
               com.setNum((int) System.currentTimeMillis());
               
               
               DatabaseConnector db = new DatabaseConnector(Messages.this);
               db.open();
               db.enterMessage(com);
               db.close();
               
               new PopulateContactMain().execute();
               new SendMessageTask().execute(mess);
               
               message.setText("");
               
            }
        });
/*
  		ListView listView = (ListView) findViewById(R.id.conversationList);
  		listView.setOnItemClickListener(new OnItemClickListener(){
  			public void onItemClick(AdapterView<?> parent, View view, int position, long id){
  				TextView txt = (TextView) view.findViewById(R.id.comment);
  				String test = Integer.toString(txt.getGravity());
  				Toast.makeText(Messages.this, test, Toast.LENGTH_SHORT).show();
		}
  		});  */
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_messages, menu);
		return true;
	}
	
	//async task via database
	public void populateConversation(){
	
		
		
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		if(item.getItemId() == R.id.menu_delete_conversation){
			DatabaseConnector db = new DatabaseConnector(this);
			db.open();
			db.deleteConversation(user, buddy);
			db.close();
			new PopulateContactMain().execute();
			
			return true;
		}else
			return false;
	}
	
	//when click enter upload the query in textbox
	//then clear
	//display
	private class PopulateContactMain extends AsyncTask<String, Object, List<Comment>>
	{
		//the main screen java file goes inside of parameter 
		//DBAdapter is my database class
		private DatabaseConnector dbAdapter = new DatabaseConnector(Messages.this);
		
		
		@Override
		protected List<Comment> doInBackground(String...objects){
			dbAdapter.open();
			return dbAdapter.populateMessages(user, buddy);
			
		}
		
		protected void onPostExecute(List<Comment> result)
		{			
			
	  		ListView listView;
	  		//Toast.makeText(Messages.this, result.get(0).getComment(), Toast.LENGTH_SHORT).show();
	  		listView = (ListView) findViewById(R.id.conversationList);
	  		adapter = new MessageListViewAdapter(Messages.this, R.layout.activity_messages, result);
	  		listView.setAdapter(adapter);
			dbAdapter.close();
		}

	}
	
	public class SendMessageTask extends AsyncTask<MessageObject, Void, Boolean>
	{
		@Override
		protected Boolean doInBackground(MessageObject... params)
		{
			// TODO: attempt authentication against a network service.
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(
					"http://softeng.cs.uwosh.edu/students/cs342g6/upload_message.php");
			Boolean response = false;
			try
			{
				// Convert the login object to XML
				XStream xstream = new XStream(new DomDriver("UTF-8"));
				xstream.alias("Login", LoginObject.class);
				String xml = xstream.toXML(params[0]);

				// Pass the XML as a StringEntity
				StringEntity se = new StringEntity(xml, HTTP.UTF_8);
				se.setContentType("text/xml");
				httppost.setEntity(se);
				System.out.println("MADE IT TO RESPONSE");
				HttpResponse httpresponse = httpclient.execute(httppost);
				HttpEntity resEntity = httpresponse.getEntity();
				String resp = EntityUtils.toString(resEntity);
				System.out.println(resp);
				if (response)
					System.out.println("true");
				else
					System.out.println("false");
			}
			catch (ClientProtocolException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return response;
		}

		@Override
		protected void onPostExecute(Boolean success)
		{

			if (success)
			{
				System.out.println("success");
				//finish()
			}
			else
			{
				
			}
		}

	}
}
